package com.zhou.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

import java.util.concurrent.TimeUnit;

@Configuration
public class JedisUtil {
    @Autowired
    private  RedisTemplate redisTemplate;

    //对象插入，JSON序列化
    public void RedisSet(String key,Object value){

        try {
            String serialize = JsonUtil.serialize(value);
            //选择操作模式：key-value
            ValueOperations ops = redisTemplate.opsForValue();
            ops.set(key,serialize,60, TimeUnit.MINUTES);  //添加age=18 存活时间为1分钟 TimeUnit.MINUTES分钟
            //ops.setIfAbsent(key,value); //只添加 setnx
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    //对象读取
    public <T>T RedisGet(String key,Class<T> clazz){
        //选择操作模式：key-value
        ValueOperations ops = redisTemplate.opsForValue();
        Object object = ops.get(key);  //获取
        T deserialize = null;
        try {
            deserialize = JsonUtil.deserialize(object.toString(), clazz);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return deserialize;
    }


}
